<template>
  <div class="showdata-container">
    <SimpleSidebar />
    <div class="main-content">
      <el-row :gutter="20">
        <!-- 视频热度展示 -->
        <el-col :span="24">
          <el-card class="data-card">
            <template #header>
              <div class="card-header">
                <span>视频热度排行</span>
              </div>
            </template>
            <div class="chart-container" ref="videoChartRef"></div>
          </el-card>
        </el-col>
      </el-row>

      <el-row :gutter="20" class="mt-20">
        <!-- 标签热度展示 -->
        <el-col :span="12">
          <el-card class="data-card">
            <template #header>
              <div class="card-header">
                <span>标签热度排行</span>
                <el-button
                    type="text"
                    style="color: #409EFF"
                    @click="handleBackToTags"
                >
                  返回标签热度
                </el-button>
              </div>
            </template>
            <div class="chart-container" ref="tagChartRef"></div>
          </el-card>
        </el-col>

        <!-- 用户喜好展示 -->
        <el-col :span="12">
          <el-card class="data-card">
            <template #header>
              <div class="card-header">
                <span>用户喜好分析</span>
              </div>
            </template>
            <el-table
                :data="userFlavorData"
                style="width: 100%"
                height="300"
                :header-cell-style="{
              background: '#f5f7fa',
              color: '#606266',
              fontWeight: 'bold',
              textAlign: 'center'
            }"
                :cell-style="{
              textAlign: 'center'
            }"
                :row-class-name="tableRowClassName"
            >
              <el-table-column prop="uid" label="用户ID" width="100">
                <template #default="scope">
                  <el-tag
                      size="small"
                      effect="plain"
                      type="info"
                      style="cursor: pointer"
                  >
                    {{ scope.row.uid }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="tname" label="标签名称" width="120">
                <template #default="scope">
                  <el-tag
                      size="small"
                      :type="getTagType(scope.row.tname)"
                  >
                    {{ scope.row.tname }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="tpercent" label="喜好占比" width="120">
                <template #default="scope">
                  <el-progress
                      :percentage="calculatePercentage(scope.row.tpercent)"
                      :color="getProgressColor(scope.row.tpercent)"
                      :stroke-width="15"
                  />
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-col>
      </el-row>

      <div class="action-area">
        <el-button type="primary" size="large" @click="goToAIAnalyse">进行AI分析</el-button>
        <el-button type="success" size="large" @click="goToExportData">导出数据</el-button>
      </div>

      <div class="pagination-container">
        <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 30, 50]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import {ref, onMounted, onUnmounted} from 'vue'
import {useRouter} from 'vue-router'
import * as echarts from 'echarts'
import Service from '@/router/interceptor.js';  // 新增导入封装的axios实例
import {ElMessage} from 'element-plus'
import {useAnalysisStore} from '@/store/analysis'
import SimpleSidebar from "@/views/chart/SimpleSidebar.vue";

const router = useRouter()
const analysisStore = useAnalysisStore()
const videoChartRef = ref(null)
const tagChartRef = ref(null)
let videoChart = null
let tagChart = null
let isShowingUserTags = ref(false)
let currentUserId = ref(null)

// 数据ref
const videoRankData = ref([])
const tabRankData = ref([])
const userFlavorData = ref([])
const userFullTagData = ref({})

// 添加组件名称
const componentName = 'ShowData'

// 添加分页参数
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 修改模拟数据中的 vid 类型
const mockVideoData = [
  {vid: 100001, views: 1500},
  {vid: 100002, views: 1200},
  {vid: 100003, views: 1000},
  {vid: 100004, views: 800},
  {vid: 100005, views: 600},
  {vid: 100006, views: 500},
  {vid: 100007, views: 400},
  {vid: 100008, views: 300},
  {vid: 100009, views: 200},
  {vid: 100010, views: 100}
]

const mockTagData = [
  {tname: '科技', cnt: 500},
  {tname: '娱乐', cnt: 400},
  {tname: '教育', cnt: 300},
  {tname: '游戏', cnt: 250},
  {tname: '音乐', cnt: 200},
  {tname: '体育', cnt: 180},
  {tname: '美食', cnt: 160},
  {tname: '旅游', cnt: 140},
  {tname: '动漫', cnt: 120},
  {tname: '时尚', cnt: 100}
]

const mockUserFlavorData = [
  {uid: 200001, tname: '科技', tpercent: '4/5'},
  {uid: 200002, tname: '娱乐', tpercent: '3/4'},
  {uid: 200003, tname: '教育', tpercent: '2/3'},
  {uid: 200004, tname: '游戏', tpercent: '3/5'},
  {uid: 200005, tname: '音乐', tpercent: '4/5'},
  {uid: 200006, tname: '体育', tpercent: '2/3'},
  {uid: 200007, tname: '美食', tpercent: '3/4'},
  {uid: 200008, tname: '旅游', tpercent: '1/2'},
  {uid: 200009, tname: '动漫', tpercent: '4/5'},
  {uid: 200010, tname: '时尚', tpercent: '2/3'}
]

const mockUserFullTagData = {
  '200001': [
    {tname: '科技', tpercent: '4/5'},
    {tname: '教育', tpercent: '3/4'},
    {tname: '游戏', tpercent: '2/3'},
    {tname: '娱乐', tpercent: '1/2'},
    {tname: '音乐', tpercent: '2/5'},
    {tname: '体育', tpercent: '1/3'},
    {tname: '美食', tpercent: '1/4'},
    {tname: '旅游', tpercent: '1/5'},
    {tname: '动漫', tpercent: '1/5'},
    {tname: '时尚', tpercent: '1/6'}
  ],
  '200002': [
    {tname: '娱乐', tpercent: '4/5'},
    {tname: '音乐', tpercent: '3/4'},
    {tname: '游戏', tpercent: '2/3'},
    {tname: '科技', tpercent: '1/2'},
    {tname: '教育', tpercent: '2/5'},
    {tname: '体育', tpercent: '1/3'},
    {tname: '美食', tpercent: '1/4'},
    {tname: '旅游', tpercent: '1/5'},
    {tname: '动漫', tpercent: '1/5'},
    {tname: '时尚', tpercent: '1/6'}
  ],
  '200003': [
    {tname: '教育', tpercent: '4/5'},
    {tname: '科技', tpercent: '3/4'},
    {tname: '游戏', tpercent: '2/3'},
    {tname: '娱乐', tpercent: '1/2'},
    {tname: '音乐', tpercent: '2/5'},
    {tname: '体育', tpercent: '1/3'},
    {tname: '美食', tpercent: '1/4'},
    {tname: '旅游', tpercent: '1/5'},
    {tname: '动漫', tpercent: '1/5'},
    {tname: '时尚', tpercent: '1/6'}
  ],
  '200004': [
    {tname: '游戏', tpercent: '4/5'},
    {tname: '科技', tpercent: '3/4'},
    {tname: '娱乐', tpercent: '2/3'},
    {tname: '教育', tpercent: '1/2'},
    {tname: '音乐', tpercent: '2/5'},
    {tname: '体育', tpercent: '1/3'},
    {tname: '美食', tpercent: '1/4'},
    {tname: '旅游', tpercent: '1/5'},
    {tname: '动漫', tpercent: '1/5'},
    {tname: '时尚', tpercent: '1/6'}
  ],
  '200005': [
    {tname: '音乐', tpercent: '4/5'},
    {tname: '娱乐', tpercent: '3/4'},
    {tname: '游戏', tpercent: '2/3'},
    {tname: '科技', tpercent: '1/2'},
    {tname: '教育', tpercent: '2/5'},
    {tname: '体育', tpercent: '1/3'},
    {tname: '美食', tpercent: '1/4'},
    {tname: '旅游', tpercent: '1/5'},
    {tname: '动漫', tpercent: '1/5'},
    {tname: '时尚', tpercent: '1/6'}
  ],
  '200006': [
    {tname: '体育', tpercent: '4/5'},
    {tname: '游戏', tpercent: '3/4'},
    {tname: '娱乐', tpercent: '2/3'},
    {tname: '科技', tpercent: '1/2'},
    {tname: '教育', tpercent: '2/5'},
    {tname: '音乐', tpercent: '1/3'},
    {tname: '美食', tpercent: '1/4'},
    {tname: '旅游', tpercent: '1/5'},
    {tname: '动漫', tpercent: '1/5'},
    {tname: '时尚', tpercent: '1/6'}
  ],
  '200007': [
    {tname: '美食', tpercent: '4/5'},
    {tname: '旅游', tpercent: '3/4'},
    {tname: '娱乐', tpercent: '2/3'},
    {tname: '科技', tpercent: '1/2'},
    {tname: '教育', tpercent: '2/5'},
    {tname: '音乐', tpercent: '1/3'},
    {tname: '体育', tpercent: '1/4'},
    {tname: '游戏', tpercent: '1/5'},
    {tname: '动漫', tpercent: '1/5'},
    {tname: '时尚', tpercent: '1/6'}
  ],
  '200008': [
    {tname: '旅游', tpercent: '4/5'},
    {tname: '美食', tpercent: '3/4'},
    {tname: '娱乐', tpercent: '2/3'},
    {tname: '科技', tpercent: '1/2'},
    {tname: '教育', tpercent: '2/5'},
    {tname: '音乐', tpercent: '1/3'},
    {tname: '体育', tpercent: '1/4'},
    {tname: '游戏', tpercent: '1/5'},
    {tname: '动漫', tpercent: '1/5'},
    {tname: '时尚', tpercent: '1/6'}
  ],
  '200009': [
    {tname: '动漫', tpercent: '4/5'},
    {tname: '游戏', tpercent: '3/4'},
    {tname: '娱乐', tpercent: '2/3'},
    {tname: '科技', tpercent: '1/2'},
    {tname: '教育', tpercent: '2/5'},
    {tname: '音乐', tpercent: '1/3'},
    {tname: '体育', tpercent: '1/4'},
    {tname: '美食', tpercent: '1/5'},
    {tname: '旅游', tpercent: '1/5'},
    {tname: '时尚', tpercent: '1/6'}
  ],
  '200010': [
    {tname: '时尚', tpercent: '4/5'},
    {tname: '娱乐', tpercent: '3/4'},
    {tname: '游戏', tpercent: '2/3'},
    {tname: '科技', tpercent: '1/2'},
    {tname: '教育', tpercent: '2/5'},
    {tname: '音乐', tpercent: '1/3'},
    {tname: '体育', tpercent: '1/4'},
    {tname: '美食', tpercent: '1/5'},
    {tname: '旅游', tpercent: '1/5'},
    {tname: '动漫', tpercent: '1/6'}
  ]
}

// API请求函数
const fetchVideoRankData = async () => {
  try {
    const response = await Service.get('/api/videoRank/loadDataList', {
      params: {
        pageNo: 1,
        pageSize: 10
      }
    })
    if (response.data && response.code === 200) {
      videoRankData.value = response.data.list
      total.value = response.data.totalCount
      
    }
    initVideoChart()
  } catch (error) {
   const errorMessage = error.response?.data?.info
     || error.response?.data?.message 
     || error.message 
     || '请求失败';
   ElMessage.error(errorMessage);
    initVideoChart()
  }
}

const fetchTagRankData = async () => {
  try {
    const response = await Service.get('/api/tabRank/loadDataList', {
      params: {
        pageNo: 1,
        pageSize: 10
      }
    })
    if (response.data && response.code === 200) {
      tabRankData.value = response.data.list.map(item => ({
        tname: item.tname || item.name,
        cnt: item.cnt || item.count || 0
      }))
      total.value = response.data.totalCount
    } else {
      console.warn('API返回数据格式异常，使用模拟数据')
      tabRankData.value = mockTagData
    }
    initTagChart()
  } catch (error) {
    const errorMessage = error.response?.data?.info
      || error.response?.data?.message 
      || error.message 
      || '请求失败';
    ElMessage.error(errorMessage);
    initTagChart()
  }
}

const fetchUserFlavorData = async () => {
  try {
    const response = await Service.get('/api/userFlavor/loadDataList', {
      params: {
        pageNo: 1,
        pageSize: 10
      }
    })
    console.log(response)
    if (response.data && response.code === 200) {
      userFlavorData.value = response.data.list.map(item => ({
        uid: item.uid,
        tname: item.tname,
        tpercent: `${Math.round(parseFloat(item.tpercent) * 100)}/100`
      }))
      total.value = response.data.totalCount
      console.log('用户喜好数据:', userFlavorData.value)
    } else {
      console.warn('API返回数据格式异常，使用模拟数据')
      userFlavorData.value = mockUserFlavorData
    }
  } catch (error) {
    const errorMessage = error.response?.data?.info
      || error.response?.data?.message 
      || error.message 
      || '请求失败';
    ElMessage.error(errorMessage);
  }
}

// const fetchUserFullTagData = async (userId) => {
//   try {
//     const response = await Service.get(`/api/userFlavor/getUserTags/${userId}`)
//     if (response.data && response.code === 200) {
//       const userData = response.data.list.map(item => ({
//         tname: item.tname,
//         tpercent: item.tpercent
//       }))
//       userFullTagData.value[userId] = userData
//       return userData
//     } else {
//       console.warn('API返回数据格式异常，使用模拟数据')
//       const mockData = mockUserFullTagData[userId]
//       userFullTagData.value[userId] = mockData
//       return mockData
//     }
//   } catch (error) {
//     console.warn('API请求失败，使用模拟数据:', error)
//     const mockData = mockUserFullTagData[userId]
//     userFullTagData.value[userId] = mockData
//     return mockData
//   }
// }

// 修改图表初始化函数中的显示格式
const initVideoChart = () => {
  if (videoChartRef.value) {
    // 按观看次数降序排序
    const sortedData = [...videoRankData.value].sort((a, b) => b.views - a.views)

    videoChart = echarts.init(videoChartRef.value)
    const option = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        },
        formatter: function (params) {
          return `视频ID: ${params[0].name}<br/>观看次数: ${params[0].value}`
        }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: sortedData.map(item => item.vid.toString()),  // 转换为字符串显示
        axisLabel: {
          interval: 0,
          rotate: 30
        }
      },
      yAxis: {
        type: 'value',
        name: '观看次数'
      },
      series: [
        {
          name: '观看次数',
          type: 'bar',
          data: sortedData.map(item => item.views),
          barWidth: '40%',
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              {offset: 0, color: '#83bff6'},
              {offset: 0.5, color: '#188df0'},
              {offset: 1, color: '#188df0'}
            ])
          },
          label: {
            show: true,
            position: 'top',
            formatter: '{c}',
            fontSize: 12,
            color: '#606266'
          }
        }
      ]
    }
    videoChart.setOption(option)
  }
}

// 初始化标签热度图表
const initTagChart = () => {
  handleBackToTags()
}

// 监听窗口大小变化，调整图表大小
const handleResize = () => {
  videoChart?.resize()
  tagChart?.resize()
}

onMounted(async () => {
  // 并行请求所有初始数据
  await Promise.all([
    fetchVideoRankData(),
    fetchTagRankData(),
    fetchUserFlavorData()
  ])

  window.addEventListener('resize', handleResize)
})

// 修改路由跳转
const goToAIAnalyse = () => {
  try {
    const analysisStore = useAnalysisStore()
    const analysisData = {
      videoRank: videoRankData.value,
      tabRank: tabRankData.value,
      userFlavor: userFlavorData.value
    }

    // 保存数据到 store
    analysisStore.setAnalysisData(analysisData)

    // 跳转到分析页面
    router.push({name: 'aianalyse'})
  } catch (error) {
    console.error('跳转失败:', error)
    ElMessage.error('跳转失败，请稍后重试')
  }
}

// 修改导出数据路由跳转
const goToExportData = () => {
  try {
    const exportData = {
      videoRank: videoRankData.value,
      tabRank: tabRankData.value,
      userFlavor: userFlavorData.value
    }

    // 保存数据到 store
    analysisStore.setExportData(exportData)

    // 跳转到导出页面
    router.push({name:'exportdata'})
  } catch (error) {
    console.error('跳转失败:', error)
    ElMessage.error('跳转失败，请稍后重试')
  }
}

const tableRowClassName = ({rowIndex}) => {
  return rowIndex % 2 === 0 ? 'even-row' : 'odd-row'
}

const getTagType = (tname) => {
  const typeMap = {
    '科技': 'primary',
    '娱乐': 'success',
    '教育': 'warning',
    '游戏': 'danger',
    '音乐': 'info'
  }
  return typeMap[tname] || 'info'
}

const calculatePercentage = (fraction) => {
  const [numerator, denominator] = fraction.split('/').map(Number)
  return Math.round((numerator / denominator) * 100)
}

const getProgressColor = (fraction) => {
  const percentage = calculatePercentage(fraction)
  if (percentage >= 75) return '#67C23A'
  if (percentage >= 50) return '#409EFF'
  if (percentage >= 25) return '#E6A23C'
  return '#F56C6C'
}

// 修改用户点击处理函数
const handleUserClick = async (userData) => {
  const userId = userData.uid.toString() // 转换为字符串用作对象键
  let userTags = userFullTagData.value[userId]
  
  if (!userTags) {
    userTags = await fetchUserFullTagData(userId)
    if (!userTags) {
      ElMessage.warning('未找到该用户的标签数据')
      return
    }
  }

  if (tagChartRef.value) {
    // 销毁之前的实例
    if (tagChart) {
      tagChart.dispose()
    }

    tagChart = echarts.init(tagChartRef.value)
    const option = {
      title: {
        text: `用户${userId}的标签偏好`,
        left: 'center',
        textStyle: {
          fontSize: 16,
          fontWeight: 'bold'
        }
      },
      tooltip: {
        trigger: 'axis',
        formatter: '{b}: {c}%',
        axisPointer: {
          type: 'shadow'
        }
      },
      grid: {
        top: '15%',
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: userTags.map(tag => tag.tname),
        axisLabel: {
          interval: 0,
          rotate: 30
        }
      },
      yAxis: {
        type: 'value',
        name: '喜好程度(%)',
        max: 100,
        splitLine: {
          show: true,
          lineStyle: {
            type: 'dashed'
          }
        }
      },
      series: [
        {
          name: '喜好程度',
          type: 'bar',
          data: userTags.map(tag => ({
            value: calculatePercentage(tag.tpercent),
            itemStyle: {
              color: getProgressColor(tag.tpercent)
            }
          })),
          label: {
            show: true,
            position: 'top',
            formatter: '{c}%'
          }
        }
      ]
    }
    tagChart.setOption(option)
  }
}

// 修改返回按钮点击事件处理函数
const handleBackToTags = () => {
  if (tagChartRef.value) {
    // 销毁之前的实例
    if (tagChart) {
      tagChart.dispose()
    }

    tagChart = echarts.init(tagChartRef.value)
    const option = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        },
        formatter: function (params) {
          return `${params[0].name}: ${params[0].value}`
        }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: tabRankData.value.map(item => item.tname),
        axisLabel: {
          interval: 0
        }
      },
      yAxis: {
        type: 'value',
        name: '出现次数',
        max: 500,
        splitLine: {
          show: true,
          lineStyle: {
            type: 'dashed'
          }
        }
      },
      series: [
        {
          name: '出现次数',
          type: 'bar',
          data: tabRankData.value.map(item => item.cnt),
          barWidth: '40%',
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              {offset: 0, color: '#ff9a9e'},
              {offset: 1, color: '#fad0c4'}
            ])
          },
          label: {
            show: true,
            position: 'top',
            fontSize: 12,
            color: '#606266'
          }
        }
      ]
    }
    tagChart.setOption(option)
  }
}

// 修改分页处理函数
const handleCurrentChange = (val) => {
  currentPage.value = val
  Promise.all([
    fetchVideoRankData(),
    fetchTagRankData(),
    fetchUserFlavorData()
  ])
}

const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  Promise.all([
    fetchVideoRankData(),
    fetchTagRankData(),
    fetchUserFlavorData()
  ])
}

// 在组件卸载时清理图表实例
onUnmounted(() => {
  if (videoChart) {
    videoChart.dispose()
  }
  if (tagChart) {
    tagChart.dispose()
  }
  window.removeEventListener('resize', handleResize)
})
</script>

<style scoped>
.showdata-container {
  display: flex;
  min-height: 100vh;
  background: linear-gradient(135deg, #b6e0ff 0%, #f7d9ff 100%);
}

.main-content {
  flex: 1;
  padding: 20px;
  margin-left: 220px;
  width: calc(100% - 220px);
}

.main-content .mt-20 {
  margin-top: 20px;
}

.main-content .data-card {
  margin-bottom: 20px;
}

.main-content .card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.main-content .action-area {
  margin-top: 20px;
  text-align: center;
}

.main-content .chart-container {
  height: 300px;
  width: 100%;
}

.main-content .el-table .even-row {
  background-color: #fafafa;
}

.main-content .el-table .odd-row {
  background-color: #ffffff;
}

.main-content .el-table td {
  padding: 8px 0;
}

.main-content .el-progress {
  margin: 0 10px;
}

.main-content .pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style>